<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>最接近的三数之和</title>
</head>
<body>
  <script>
    function fn(nums, target) {
      let N = nums.length
      let res = Number.MAX_SAFE_INTEGER
      nums.sort((a, b) => a - b)
      for (let i = 0; i < N; i++) {
        let left = i + 1
        let right = N - 1
        while (left < right) {
          let sum = nums[i] + nums[left] + nums[right]
          if (Math.abs(sum - target) < Math.abs(res - target)) {
            res = sum
          }
          if (sum < target) {
            left++
          } else if (sum > target) {
            right--
          } else {
            return sum
          }
        }
      }
      return res
    }
    console.log(fn([-1, 2, 1, -4], 1))
  </script>
</body>
</html>